package com.pan.service;

import com.pan.constants.DatabaseInfo;
import com.pan.dao.User;
import com.pan.dao.UserDAO;
import com.pan.dao.UserDAOImpl;
import com.pan.util.CheckAuth;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet("/upload")
@MultipartConfig
public class UploadFile extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String token = request.getParameter("token");
        if (!CheckAuth.checkToken(token)) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }
        UserDAO userDAO = UserDAOImpl.getInstance();
        User user = userDAO.getUserByToken(token);
        Part filePart = request.getPart("files");
        String fileName = filePart.getSubmittedFileName();
        String path = request.getParameter("path");
        String filePath = DatabaseInfo.FILE_PATH + "\\" + user.getFilePath() + "\\" + path + "\\" + fileName;
        filePart.write(filePath);
    }
}
